<template>
  <div class="header">
    <div class="header-left">
      <img
        src="@/assets/images/logo_text.png"
        alt="logo"
      >
    </div>
    <div class="header-right">
      <ul class="left-operate">
        <li
          class="app-icon"
          @mouseenter="showMyAppBox"
          @mouseleave="hideMyAppBox"
          v-if="showMyAppIcon"
        >
          <sc-icon name="iconyingyongguanli-01"></sc-icon>

          <div
            class="app-box scroll-bar"
            v-if="showMyApp"
          >
            <ul
              class="app-list"
              @mouseleave="hideMyAppBox"
            >
              <li
                v-for="item in appData"
                :key="item.id"
                @click="chooseApp(item)"
              >
                <div class="app-icon-box">
                  <img
                    src="@/assets/images/app_icon.png"
                    alt="icon"
                  >
                </div>
                <div class="app-info">
                  <p class="app-title">{{ item.title }}</p>
                  <p class="app-describe">{{ item.describe }}</p>
                </div>
              </li>
            </ul>
          </div>
        </li>
      </ul>

      <div class="right-operate">
        <ul class="operate-icon">
          <li>
            <sc-icon
              name="iconsousuo-01"
              class="search-iconfont"
              v-if="!showSearchBox"
              @click.native="showSearchBoxFn"
            ></sc-icon>
            <div
              class="serach-container"
              v-if="showSearchBox"
            >
              <el-input
                v-model="searchText"
                prefix-icon="el-icon-search"
                :placeholder="$t('search.placeholder')"
                clearable
                @input="searchFn"
                @blur="hideSearchBox"
                ref="search-input"
              ></el-input>
              <div
                class="search-suggest-box"
                v-if="showSuggest"
              >
                <ul
                  class="search-suggest-list"
                  v-if="suggestData.length"
                >
                  <li
                    v-for="item in suggestData"
                    :key="item.id"
                    @click="chooseSuggest(item)"
                  >
                    <span
                      class="suggest-tag-name"
                      v-html="item.matchingName"
                    ></span>
                    <span class="suggest-tag-content">
                      <template v-if="item.type === 1">
                        <i>{{ $t('search.app') }}</i>
                      </template>
                      <template v-else>
                        <i>{{ $t('search.belongApp') }}：</i>
                        {{ item.parent }}
                      </template>
                    </span>
                  </li>
                </ul>
                <div
                  class="no-suggest-data"
                  v-if="showNoSuggestBox"
                >{{ $t('search.noDataHint') }}</div>
              </div>
            </div>
          </li>
          <li @click="showHeaderMask(1)">
            <sc-icon name="iconxiaoxitongzhi"></sc-icon>
            <span
              class="badge-box-text"
              v-if="msgNum > 0"
            >{{ msgNum > 99 ? '99+' : msgNum }}</span>
          </li>
        </ul>
        <div
          class="avatar-box"
          @click="showHeaderMask(2)"
        >
          <img
            :src="avatar ? avatar : defaultAvatar"
            alt="avatar"
          >
        </div>
      </div>
    </div>

    <div
      v-if="maskVisible"
      class="header-mask-container"
    >
      <div
        class="header-mask-top"
        @click="closeHeaderMask"
      ></div>
      <div class="header-mask-wrapper">
        <div
          class="header-mask-wrapper-left"
          @click="closeHeaderMask"
        ></div>
        <div class="header-mask-content">
          <MessageCenter
            v-if="msgBoxVisible"
            :msgBoxVisible.sync="msgBoxVisible"
            @closeHeaderMask="closeHeaderMask"
            @updateUnreadMsgNum="updateUnreadMsgNum"
          />

          <PersonalInfo
            v-if="personalVisible"
            :personalVisible.sync="personalVisible"
            @closeHeaderMask="closeHeaderMask"
            @editAvatar="editAvatar"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import MessageCenter from './components/MessageCenter.vue';
import PersonalInfo from './components/PersonalInfo.vue';
import { messageStatus } from '@/api/message';
import { searchList } from '@/api/search';
import { userInfo } from '@/api/user';

export default {
  name: 'Header',
  components: {
    MessageCenter,
    PersonalInfo
  },
  data() {
    return {
      showMyAppIcon: true, //显示我的应用图标
      appData: [], //应用数据
      maskVisible: false, //遮罩
      showMyApp: false, //是否显示我的应用
      msgBoxVisible: false, //是否显示消息弹窗
      personalVisible: false, //是否显示个人信息弹窗
      msgNum: 0, //未读消息数量
      searchText: '', //搜索关键字
      suggestData: [], //搜索建议
      showSearchBox: false, //是否显示搜索框
      showSuggest: false, //是否显示搜索提示
      showNoSuggestBox: false, //是否显示未搜索到值的提示
      timer: '', //定时器
      avatar: '', //用户头像
      defaultAvatar: require('@/assets/images/avatar_big.png') //默认头像
    };
  },
  created() {
    let isMyApp = this.getUrlParam('isMyApp');
    if (isMyApp) {
      this.showMyAppIcon = false;
    }

    this.appData = [
      {
        id: 0,
        url: '/myApp/',
        title: '我的应用',
        describe: '我的应用'
      },
      {
        id: 1,
        url: '/ams/',
        title: '应用管理',
        describe: '应用管理'
      },
      {
        id: 2,
        url: '/marketCenterApp/',
        title: '营销中心',
        describe: '营销中心'
      },
      {
        id: 3,
        url: '/systemManageApp/',
        title: '系统管理',
        describe: '系统管理'
      },
      {
        id: 4,
        url: '/deviceApp/',
        title: '设备中心',
        describe: '设备中心'
      }
    ];

    this.initFn();
  },
  methods: {
    // 初始请求
    initFn() {
      this.getUnreadMsgNum();
      this.getUserInfo();
    },
    // 获取用户信息
    getUserInfo() {
      userInfo().then(res => {
        let { avatar, language, theme } = res.data;
        this.avatar = avatar;

        this.initThemeAndLanguage(language, theme);
      });
    },
    // 初始化主题和语言
    initThemeAndLanguage(language, theme) {
      this.$i18n.locale = language;
      this.$store.dispatch('changeTheme', theme);

      this.postMessageFn({
        type: 'changeLanguage',
        data: {
          language
        }
      });
      this.postMessageFn({
        type: 'changeTheme',
        data: {
          theme
        }
      });
    },
    // 选择应用
    chooseApp(item) {
      this.hideMyAppBox();

      let origin = window.location.origin;
      let href = `${origin}${item.url}`;

      this.postMessageFn({
        type: 'chooseApp',
        data: {
          href
        }
      });
    },
    // 获取未读消息条数
    getUnreadMsgNum() {
      messageStatus().then(res => {
        this.msgNum = res.data.unread || 0;
      });
    },
    // 更新未读消息条数
    updateUnreadMsgNum() {
      this.getUnreadMsgNum();
    },
    // 获取url参数
    getUrlParam(name) {
      let reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)');
      let r = window.location.search.substr(1).match(reg);
      if (r !== null) return decodeURIComponent(r[2]);
      return null;
    },
    // 修改header元素显示层级
    changeParentZindex(zIndex) {
      this.postMessageFn({
        type: 'changeParentZindex',
        data: {
          zIndex
        }
      });
    },
    // 显示我的应用
    showMyAppBox() {
      this.changeParentZindex(2);
      this.showMyApp = true;
    },
    // 隐藏我的应用
    hideMyAppBox() {
      this.changeParentZindex(1);
      this.showMyApp = false;
    },
    // ifrma页面传参
    postMessageFn(data) {
      let parentOrigin = document.referrer;
      window.parent.postMessage(data, parentOrigin);
    },
    // 防抖
    debounce(fn, delay = 300) {
      if (this.timer) {
        clearTimeout(this.timer);
        this.timer = null;
      }

      this.timer = setTimeout(() => {
        fn();
      }, delay);
    },
    // 选择搜索结果
    chooseSuggest(item) {
      this.hideSearchBox();
    },
    // 显示搜索框
    showSearchBoxFn() {
      this.showSearchBox = true;
      this.$nextTick(() => {
        this.$refs['search-input'].$refs.input.focus();
      });
      this.changeParentZindex(2);
    },
    // 隐藏搜索框
    hideSearchBox() {
      setTimeout(() => {
        this.searchText = '';
        this.suggestData = [];
        this.showSearchBox = false;
        this.showSuggest = false;
        this.showNoSuggestBox = false;
      }, 100);
      this.changeParentZindex(1);
    },
    // 搜索
    searchFn() {
      this.debounce(() => {
        if (this.searchText) {
          searchList({
            keyword: this.searchText
          }).then(res => {
            if (res.data.list.length) {
              let data = res.data.list;
              data.map(item => {
                if (this.searchText) {
                  if (item.name.search(this.searchText) !== -1) {
                    item.matchingName = item.name.replace(this.searchText, `<i>${this.searchText}</i>`);
                  }
                } else {
                  item.matchingName = item.name;
                }
              });
              this.suggestData = data;
              this.showSuggest = true;
              this.showNoSuggestBox = false;
            } else {
              this.showSuggest = true;
              this.showNoSuggestBox = true;
            }
          });
        } else {
          this.showSuggest = false;
          this.showNoSuggestBox = false;
        }
      });
    },
    // 显示消息窗口
    showHeaderMask(type) {
      this.maskVisible = true;
      this.changeParentZindex(2);
      if (type === 1) {
        // 消息中心
        this.msgBoxVisible = true;
        this.personalVisible = false;
      } else {
        // 个人中心
        this.personalVisible = true;
        this.msgBoxVisible = false;
      }
    },
    // 修改用户头像
    editAvatar(src) {
      this.avatar = src;
    },
    // 隐藏头部弹窗
    closeHeaderMask() {
      this.msgBoxVisible = false;
      this.personalVisible = false;
      this.maskVisible = false;
      this.changeParentZindex(1);
    }
  }
};
</script>

<style lang="scss" scoped>
.header {
  flex-shrink: 0;
  display: flex;
  width: 100%;
  height: 64px;
  background: linear-gradient(
    var(--gradient-deg),
    var(--gradient-first-color-opacity),
    var(--gradient-second-color-opacity)
  );

  .header-left {
    flex-shrink: 0;
    display: flex;
    justify-content: center;
    align-items: center;
    width: 220px;
    overflow: hidden;

    img {
      width: 170px;
      object-fit: cover;
    }
  }

  .header-right {
    flex: 1;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .left-operate {
      display: flex;
      align-items: center;
      height: 100%;

      > li {
        display: flex;
        justify-content: center;
        align-items: center;
        position: relative;
        width: 64px;
        height: 100%;
        color: #fff;
        font-size: 20px;

        &.app-icon {
          &:hover {
            background-color: rgba(0, 0, 0, 0.1);
          }
        }

        &.active-app-icon {
          background-color: rgba(0, 0, 0, 0.1);
        }

        .app-iconfont {
          font-size: 16px;
        }

        .app-box {
          position: absolute;
          top: 100%;
          left: -220px;
          z-index: 99;
          width: 100vw;
          height: calc(100vh - 64px);
          background-color: rgba(0, 0, 0, 0.5);
          overflow-y: auto;

          .app-list {
            display: flex;
            flex-wrap: wrap;
            gap: 30px;
            width: 100%;
            padding: 30px;
            padding-bottom: 0;
            background-color: #fff;

            > li {
              display: flex;
              flex-direction: column;
              justify-content: center;
              align-items: center;
              width: 205px;
              height: 238px;
              margin-bottom: 30px;
              border-radius: 10px;
              box-shadow: 0 0 8px #ebebeb;

              &:hover {
                box-shadow: 0 0 12px 2px var(--hover-primary);

                .app-info {
                  .app-title {
                    color: var(--color-primary);
                  }
                }
              }

              .app-icon-box {
                display: flex;
                justify-content: center;
                align-items: center;
                width: 120px;
                height: 105px;
                overflow: hidden;

                img {
                  width: 100%;
                  object-fit: cover;
                }
              }

              .app-info {
                margin-top: 32px;
                text-align: center;

                .app-title {
                  font-size: 16px;
                  color: #303133;
                }

                .app-describe {
                  margin-top: 12px;
                  font-size: 14px;
                  color: #909399;
                }
              }
            }
          }
        }
      }
    }

    .right-operate {
      display: flex;
      align-items: center;
      height: 100%;
      padding-right: 16px;

      .operate-icon {
        display: flex;
        align-items: center;
        height: 100%;

        > li {
          position: relative;
          display: flex;
          align-items: center;
          height: 100%;
          margin-left: 20px;
          color: #fff;
          font-size: 18px;

          &:hover {
            cursor: pointer;
          }

          .search-iconfont {
            opacity: 0.8;

            &:hover {
              opacity: 1;
            }
          }

          .serach-container {
            position: relative;
            width: 400px;
            height: 40px;

            .search-suggest-box {
              position: absolute;
              top: 100%;
              left: 0;
              width: 100%;
              margin-top: 6px;
              padding: 6px 15px 10px 20px;
              border-radius: 4px;
              box-shadow: 0 0 8px #bdbdbd;
              background-color: #fff;

              &::before {
                content: '';
                position: absolute;
                top: -6px;
                left: 30px;
                width: 0;
                height: 0;
                border-left: 5px solid transparent;
                border-right: 5px solid transparent;
                border-bottom: 6px solid #fff;
              }

              .search-suggest-list {
                width: 100%;

                > li {
                  display: flex;
                  justify-content: space-between;
                  align-items: center;
                  width: 100%;
                  height: 34px;
                  line-height: 34px;
                  font-size: 14px;
                  color: #606266;

                  .suggest-tag-name {
                    ::v-deep i {
                      font-style: normal;
                      color: var(--color-primary);
                    }
                  }

                  .suggest-tag-content {
                    font-size: 12px;

                    i {
                      font-style: normal;
                      color: #909399;
                    }
                  }
                }
              }

              .no-suggest-data {
                height: 34px;
                line-height: 34px;
                font-size: 14px;
                color: #606266;
              }
            }
          }

          .badge-box-text {
            position: absolute;
            top: 14px;
            left: 10px;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 18px;
            padding: 4px 6px;
            font-size: 12px;
            border-radius: 9px;
            background-color: #f15d5d;
          }
        }
      }

      .avatar-box {
        position: relative;
        display: flex;
        justify-content: center;
        align-items: center;
        width: 32px;
        height: 0;
        padding-bottom: 32px;
        margin-left: 27px;
        border-radius: 50%;
        overflow: hidden;

        img {
          position: absolute;
          top: 0;
          width: 100%;
          height: 100%;
          object-fit: cover;
        }
      }
    }
  }

  .header-mask-container {
    position: fixed;
    top: 0;
    right: 0;
    z-index: 999;
    width: 100%;
    height: 100%;

    .header-mask-top {
      width: 100%;
      height: 64px;
    }

    .header-mask-wrapper {
      display: flex;
      width: 100%;
      height: calc(100% - 64px);
      background-color: rgba(0, 0, 0, 0.5);

      .header-mask-wrapper-left {
        flex: 1;
      }

      .header-mask-content {
        width: 500px;
        height: 100%;
        background-color: #fff;
      }
    }
  }
}
</style>
